/*
 *    	@(#)@Constants.java  2017年10月23日
 *     
 *      @COPYRIGHT@
 */
package com.capinfo.accumulation.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import com.capinfo.accumulation.web.Constants;


/**
 * <p>
 * 从cookie中读取机器所属网点的id。
 * 用于在数据入库时，插入数据所属的区域。
 * </p>
 * 
 * @version 1.0
 * @author 张名扬
 */
public class DataScopePopulateFilter implements Filter {

	protected String cookieName = Constants.COOKIE_NAME_CLIENT_INFO;

	/**
	 * Take this filter out of service.
	 */
	public void destroy() {

		this.cookieName = null;
	}

	/**
	 *
	 * @param request
	 *            The servlet request we are processing
	 * @param response
	 *            The servlet response we are creating
	 * @param chain
	 *            The filter chain we are processing
	 *
	 * @exception IOException
	 *                if an input/output error occurs
	 * @exception ServletException
	 *                if a servlet error occurs
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		HttpServletRequest httpRequest = (HttpServletRequest) request;
		
		Cookie[] cookies = httpRequest.getCookies();
		
		if (cookies != null && cookies.length > 0) {
			
			for (int i = 0, j = cookies.length; i < j; i++) {
				
				Cookie cookie = cookies[i];
				if ( cookie.getName().equalsIgnoreCase(this.cookieName) ) {
					
					String value = cookie.getValue();
					if( StringUtils.isNotBlank(value) ) {
						
						Constants.THREAD_LOCAL_DATA_SCOPE_ID.set(Long.parseLong(value));
					}
					
					break;
				}
			}
		}
		
		
		// Pass control on to the next filter
		chain.doFilter(request, response);

	}

	/**
	 * Place this filter into service.
	 *
	 * @param filterConfig
	 *            The filter configuration object
	 */
	public void init(FilterConfig filterConfig) throws ServletException {

		String argCookieName = filterConfig.getInitParameter("cookieName");
		if( StringUtils.isNotBlank(argCookieName) ) {

			this.cookieName = argCookieName;
		}
	}

} // EOC
